//
//  ConversationViewController.m
//  Coding_My
//
//  Created by showXxie on 2017/8/22.
//  Copyright © 2017年 sooxie. All rights reserved.
//

#import "ConversationViewController.h"
#import "MessageCell.h"
#import "RDVTabBarController.h"
#import "UIMessageInputView.h"

@interface ConversationViewController ()<UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate,UIMessageInputViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) ODRefreshControl *refreshControl;
@property (nonatomic, assign) CGFloat preContentHeight;
@property (nonatomic, strong) UIMessageInputView *myMsgInputView;

@end

@implementation ConversationViewController

-(void)viewWillAppear:(BOOL)animated {
    //必须调用父类的方法 才能调用交换的方法 只有父类交换了方法 显示隐藏tabbar
   [super viewWillAppear:animated];

    // 弹出输入框到 keywindow
    if (_myMsgInputView) {
        [_myMsgInputView prepareToShow];
    }
    

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (_myMsgInputView) {
        [_myMsgInputView prepareToDismiss];
    }
}


- (void)test {
    NSLog(@"%s",__func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self.rdv_tabBarController setTabBarHidden:YES animated:YES];

    _myTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.backgroundColor = kColorTableBG;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tableView registerClass:[MessageCell class] forCellReuseIdentifier:kCellIdentifier_Message];
        [tableView registerClass:[MessageCell class] forCellReuseIdentifier:kCellIdentifier_MessageMedia];
        [tableView registerClass:[MessageCell class] forCellReuseIdentifier:kCellIdentifier_MessageVoice];
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView;
    });
    
    
    _myMsgInputView = [UIMessageInputView messageInputViewWithType:UIMessageInputViewContentTypePriMsg placeHolder:@"请输入私信内容"];
    _myMsgInputView.isAlwaysShow =YES;
    _myMsgInputView.delegate = self;

    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0,CGRectGetHeight(_myMsgInputView.frame), 0.0);
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;

    [self refreshLoadMore:NO];
}

#pragma mark refresh 更新聊天列表
- (void)refreshLoadMore:(BOOL)willLoadMore{
    if (!_myPriMsgs ||  _myPriMsgs.isLoading) {
        return;
    }
    _myPriMsgs.willLoadMore = willLoadMore;

    //加载更多
    if (willLoadMore) {
        if (!_myPriMsgs.canLoadMore) {
            [_refreshControl endRefreshing];
            return;
        }else{
            [_refreshControl beginRefreshing];
        }
    }
    __weak typeof(self) weakSelf = self;

    
    [[NetAPIManager manager] request_PrivateMessages:_myPriMsgs andBlock:^(id data, NSError *error) {
        
        [weakSelf.refreshControl endRefreshing];
        
        if (data) {
            
            NSArray *dicdata = data[@"data"];
            
            //消息列表数组
            NSArray *tempArr = [PrivateMessage mj_objectArrayWithKeyValuesArray:dicdata];
            
            [weakSelf.myPriMsgs configWithObj:tempArr];

            [weakSelf.myTableView reloadData];
            
            NSLog(@"%f",weakSelf.myTableView.contentSize.height);
            
            //不是加载更多 tableview滚动到最底部
            if (!weakSelf.myPriMsgs.willLoadMore) {
               
                [weakSelf scrollToBottomAnimated:NO];

            }else {
                CGFloat curContentHeight = weakSelf.myTableView.contentSize.height;
               
                CGFloat cha = curContentHeight -_preContentHeight;
                //加载更多聊天信息时设置 tableview 的偏移量
                /// 新数据后tableview 的contentsize - 旧的  + tableview的偏移量
                [weakSelf.myTableView setContentOffset:CGPointMake(0, (curContentHeight -_preContentHeight)+weakSelf.myTableView.contentOffset.y)];

                
            }
            
        }
        
 
        
        
        
    }];

    
    
}


#pragma mark Table M

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 0;
    if (_myPriMsgs.dataList) {
        row = [_myPriMsgs.dataList count];
    }
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageCell *cell;
   
    //数据倒置 row=0  20 获得最后一条数据   19
    NSUInteger curIndex = ([_myPriMsgs.dataList count] -1) - indexPath.row;
    PrivateMessage *curMsg = [_myPriMsgs.dataList objectAtIndex:curIndex];


    if (curMsg.hasMedia) {
        cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_MessageMedia forIndexPath:indexPath];
    
    }else if([curMsg isVoice]) {
       
        cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_MessageVoice forIndexPath:indexPath];

    }
    else{
        cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Message forIndexPath:indexPath];
    }

    //上一条数据 row=0时 20
    PrivateMessage *preMsg = nil;
    if (curIndex +1 < _myPriMsgs.dataList.count) {
        preMsg = [_myPriMsgs.dataList objectAtIndex:curIndex+1];
    }
    
    
    [cell setCurPriMsg:curMsg andPrePriMsg:preMsg];
    __weak typeof(self) weakSelf = self;
   
    cell.refreshMessageMediaCCellBlock = ^(CGFloat diff){
        if (ABS(diff) > 1) {
            [weakSelf.myTableView reloadData];
        }
    };
   
    return cell;

}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    PrivateMessage *preMessage = nil;
    NSUInteger curIndex = ([_myPriMsgs.dataList count] -1) - indexPath.row;
    if (curIndex +1 < _myPriMsgs.dataList.count) {
        preMessage = [_myPriMsgs.dataList objectAtIndex:curIndex+1];
    }
    return [MessageCell cellHeightWithObj:[_myPriMsgs.dataList objectAtIndex:curIndex] preObj:preMessage];
}




- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.myTableView numberOfRowsInSection:0];

    if(rows > 0) {

        [self.myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        
    }
}



#pragma mark ScrollView Delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _myTableView) {
        [_myMsgInputView isAndResignFirstResponder];
    }
}

//减速停止时
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentSize.height >CGRectGetHeight(scrollView.bounds)
        && scrollView.contentOffset.y < 5) {
        //得出当前的contennsizeH
        _preContentHeight = self.myTableView.contentSize.height;
        [self refreshLoadMore:YES];
    }
}


//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    
//    if (_myTableView == scrollView) {
//        CGSize size = scrollView.contentSize;
//
//        CGFloat offsetY = scrollView.contentOffset.y;
//        
//        NSLog(@"%f",offsetY);
//    }
//    
//}


#pragma mark UIMessageInputView M
- (void)willTranspondMessage:(PrivateMessage *)message{

    
}


#pragma mark - 发送语音
- (void)messageInputView:(UIMessageInputView *)inputView sendVoice:(NSString *)file duration:(NSTimeInterval)duration {
    VoiceMedia *vm = [[VoiceMedia alloc] init];
    vm.file = file;
    vm.duration = duration;
    [self sendPrivateMessage:vm];
}

#pragma mark  - 改变tableview的偏移量
- (void)messageInputView:(UIMessageInputView *)inputView heightToBottomChenged:(CGFloat)heightToBottom{
    

    UIEdgeInsets contentInsets= UIEdgeInsetsMake(0.0, 0.0, MAX(CGRectGetHeight(inputView.frame), heightToBottom), 0.0);
    
    // 设置tableview
    self.myTableView.contentInset = contentInsets;
    self.myTableView.scrollIndicatorInsets = contentInsets;
    

    //调整内容  static 存在全局区
    static BOOL keyboard_is_down = YES;
    static CGPoint keyboard_down_ContentOffset;
    static CGFloat keyboard_down_InputViewHeight;
    
    //heightToBottom 输入框到底部距离

    if (heightToBottom > CGRectGetHeight(inputView.frame)) {
        if (keyboard_is_down) {
            
            keyboard_down_ContentOffset = self.myTableView.contentOffset;
           
            keyboard_down_InputViewHeight = CGRectGetHeight(inputView.frame);
        }
       
        keyboard_is_down = NO;
        
        CGPoint contentOffset = keyboard_down_ContentOffset;
       
        CGFloat spaceHeight = MAX(0, CGRectGetHeight(self.myTableView.frame) - self.myTableView.contentSize.height - keyboard_down_InputViewHeight);
      
        contentOffset.y += MAX(0, heightToBottom - keyboard_down_InputViewHeight - spaceHeight);
        NSLog(@"\nspaceHeight:%.2f heightToBottom:%.2f diff:%.2f Y:%.2f", spaceHeight, heightToBottom, MAX(0, heightToBottom - CGRectGetHeight(inputView.frame) - spaceHeight), contentOffset.y);
       
        //设置tableview的偏移量
        self.myTableView.contentOffset = contentOffset;
    }else{
        //键盘收起的
        keyboard_is_down = YES;
    }

    
}




- (void)sendPrivateMessage:(id)obj{
    
    PrivateMessage *nextMsg = [PrivateMessage privateMessageWithObj:obj andFriend:_myPriMsgs.curFriend];
    
    
//    [self sendPrivateMessageWithMsg:nextMsg];


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
